import storage from 'store'
import { getEmployeeInfo, getUserInfo, login, logout } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { clientId } from '@/config'
import Vue from 'vue'
import axios from '@/utils/request'
import { findOrgTagListAll } from '@/api/login'

const user = {
  state: {
    fgs: '',
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {},
    menus: [],
    rooterMenus: [],
    activeCodes: (sessionStorage.getItem('activeCodes') || '').split(',') || [],
    userInfo: {}, // 用户信息
    // 修改密码隐藏显示
    pwd: JSON.parse(sessionStorage.getItem('pwd')) || false,
    // 修改账号隐藏显示
    account: JSON.parse(sessionStorage.getItem('account')) || false,
    businessSearchConditions: sessionStorage.getItem('businessSearchConditions') ? JSON.parse(sessionStorage.getItem('businessSearchConditions')) : {
      detSet: [],
      orgSet: [],
    },
    // 组织标签
    orgLabel: JSON.parse(sessionStorage.getItem('orgLabel' || [])),
    // 设备缩放比例
    devicePixelRatio: Number(sessionStorage.getItem('devicePixelRatio')) || 1,
    // 纠正百分比数值(需要单独加%或者vh，vw等单位)
    redressPercentage: Number(sessionStorage.getItem('redressPercentage')) || 100
  },
  getters: {
    GET_PWD(state) {
      return state.pwd
    },
    GET_ACCOUNT(state) {
      return state.account
    },
    GET_ORGLABEL(state) {
      return state.orgLabel
    },
    GET_DEVICE_PIXEL_RATIO(state){
      return state.devicePixelRatio
    },
    GET_REDRESS_PERCENTAGE(state) {
      return state.redressPercentage
    }
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_FGS: (state, fgs) => {
      state.fgs = fgs
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
    },
    SET_ROOT_MENUS: (state, rooterMenus) => {
      state.rooterMenus = rooterMenus
    },
    SET_USER: (state, user) => {
      state.userInfo = user // 用户信息
    },
    SET_ACTIVE_CODES: (state, activeCodes) => {
      // 当前选择的菜单code
      state.activeCodes = activeCodes.filter(item => !!item)
      sessionStorage.setItem('activeCodes', activeCodes.join(','))
    },
    //设置修改密码隐藏显示
    SET_PWD: (state, visible) => {
      state.pwd = visible
      sessionStorage.setItem('pwd', visible)
    },
    // 设置修改账号隐藏显示
    SET_ACCOUNT: (state, visible) => {
      state.account = visible
      sessionStorage.setItem('account', visible)
    },
    // 数据筛选结果
    SET_BUSINESS_SEARCH_CONDITIONS: (state, values) => {
      state.businessSearchConditions = values
      sessionStorage.setItem('businessSearchConditions', JSON.stringify(values))
    },
    // 设置组织标签
    SET_ORGLABEL: (state, values) => {
      state.orgLabel = values
      sessionStorage.setItem('orgLabel', JSON.stringify(values || []))
    },
    // 设置设备缩放比例
    SET_DEVICE_PIXEL_RATIO(state, values) {
      state.devicePixelRatio = values
      sessionStorage.setItem('devicePixelRatio', values)
    },
    // 设置纠正百分比数值
    SET_REDRESS_PERCENTAGE(state, values) {
      state.redressPercentage = values
      sessionStorage.setItem('redressPercentage', values)
    }
  },

  actions: {
    // 登录
    async Login({ commit }, userInfo) {
      try {
        const res = await login(userInfo);
        storage.set(ACCESS_TOKEN, res.access_token, 7 * 24 * 60 * 60 * 1000)
        if (userInfo.setToken) {
          commit('SET_TOKEN', res.access_token)
          Vue.getAcloudProvider().setAccessToken(res.access_token)
          Vue.getAcloudProvider().setRefreshToken(res.refresh_token)
          Vue.getAcloudProvider().setTokenObj(res)
        }
        return Promise.resolve(res);
      } catch (err) {
        return Promise.reject(err);
      }
      // return new Promise((resolve, reject) => {
      //   login(userInfo).then(response => {
      //     storage.set(ACCESS_TOKEN, response.access_token, 7 * 24 * 60 * 60 * 1000)
      //     if(userInfo.setToken){
      //       commit('SET_TOKEN', response.access_token)
      //       Vue.getAcloudProvider().setAccessToken(response.access_token)
      //       Vue.getAcloudProvider().setRefreshToken(response.refresh_token)
      //       Vue.getAcloudProvider().setTokenObj(response)
      //     }
      //     resolve(response)
      //   }).catch(error => {
      //     reject(error)
      //   })
      // })
    },
    GetMenus({ commit }) {
      let url = Vue.getAcloudProvider().getMenuUri() + '?resType=1&clientId=' + clientId
      return axios.get(url).then((res) => {
        let data = res.data.filter(item => item.raw.name !== 'app')
        if (data) {
          Vue.getAcloudProvider().setMenu(data)
          commit('SET_MENUS', data)
          return data
        }
      })
    },
    async GetUserInfo({ commit }, params) {
      try {
        const res = await getUserInfo(params);
        res['employee'] = await getEmployeeInfo({ ...params, userId: res.id })
        commit('SET_INFO', res)
        Vue.getAcloudProvider().setUserInfo(res)
        return Promise.resolve(res);
      } catch (err) {
        return Promise.reject(err);
      }
    },
    // 获取用户信息
    // GetInfo ({ commit }) {
    //   return new Promise((resolve, reject) => {
    //     getInfo().then(response => {
    //       const result = response.data.result
    //
    //       if (result.role && result.role.permissions.length > 0) {
    //         const role = result.role
    //         localStorage.setItem("role",JSON.stringify(role))
    //         role.permissions = result.role.permissions
    //         role.permissions.map(per => {
    //           if (per.actionEntitySet != null && per.actionEntitySet.length > 0) {
    //             const action = per.actionEntitySet.map(action => { return action.action })
    //             per.actionList = action
    //           }
    //         })
    //         role.permissionList = role.permissions.map(permission => { return permission.permissionId })
    //         commit('SET_ROLES', result.role)
    //         commit('SET_INFO', result)
    //       } else {
    //         reject(new Error('getInfo: roles must be a non-null array !'))
    //       }
    //
    //       commit('SET_NAME', { name: result.name, welcome: welcome() })
    //       commit('SET_AVATAR', result.avatar)
    //
    //       resolve(response)
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },

    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          resolve()
        }).catch(() => {
          resolve()
        }).finally(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          storage.remove(ACCESS_TOKEN)
        })
      })
    },
    /**
     * @description: 修改密码弹窗显示隐藏
     * @return {void}
     */
    pwdVisible({ commit }, visible) {
      commit('SET_PWD', visible)
    },
    /**
     * @description: 修改账号弹窗显示隐藏
     * @return {void}
     */
    accountVisible({ commit }, visible) {
      commit('SET_ACCOUNT', visible)
    },
    /**
     * @description: 清空组织标签
     * @param {function} commit 
     * @return {promise}
     */
    clearOrgLabel({ commit }) {
      commit('SET_ORGLABEL', [])
    },
    /**
     * @description: 获取组织标签
     * @param {function} commit 
     * @return {promise}
     */
    getOrgLabel({ commit }) {
      return new Promise((resolve, reject) => {
        findOrgTagListAll({}).then(({ code, data, message }) => {
          if (code === 200) {
            commit('SET_ORGLABEL', data)
            resolve()
          } else {
            reject(message)
          }
        }).catch((error) => {
          reject(error)
        })
      })
    },
    // 设置纠正数值
    setDevicePixelRatio({ commit }, { devicePixelRatio, redressPercentage }){
      commit('SET_DEVICE_PIXEL_RATIO', devicePixelRatio)
      commit('SET_REDRESS_PERCENTAGE', redressPercentage)
    }
  }
}

export default user
